package com.liukai.bishe.ui.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.liukai.bishe.R;
import com.liukai.bishe.model.doman.transaction.TransactionMessageList;
import com.liukai.bishe.model.doman.transaction.TransactionTotal;
import com.liukai.bishe.model.doman.transaction.TransactionUseTime;
import com.liukai.bishe.model.doman.transaction.TransactionUserTimeMessageList;
import com.liukai.bishe.model.doman.user.User;
import com.liukai.bishe.presenter.transactionPresenter.IFindTransactionByUsernamePresenter;
import com.liukai.bishe.presenter.transactionPresenter.ITransactionPresenter;
import com.liukai.bishe.presenter.transactionPresenter.ITransactionUserTimePresenter;
import com.liukai.bishe.presenter.transactionPresenter.impl.IFindTransactionByUsernamePresenterImpl;
import com.liukai.bishe.presenter.transactionPresenter.impl.ITransactionPresenterImpl;
import com.liukai.bishe.presenter.transactionPresenter.impl.ITransactionUserTimePresenterImpl;
import com.liukai.bishe.presenter.userPresenter.IUpdateHeadImgPresenter;
import com.liukai.bishe.ui.activity.userInfo.UserInfoActivity;
import com.liukai.bishe.ui.fragment.AnalysisFragment;
import com.liukai.bishe.ui.fragment.BaseFragment;
import com.liukai.bishe.ui.fragment.LoadFragment;
import com.liukai.bishe.ui.fragment.SettingFragment;
import com.liukai.bishe.ui.fragment.StateFragment;
import com.liukai.bishe.ui.fragment.TransactionFragment;
import com.liukai.bishe.utils.CircleDrawable;
import com.liukai.bishe.utils.Constants;
import com.liukai.bishe.utils.ToastUtil;
import com.liukai.bishe.view.IFindTransactionByUsernameCallBack;
import com.liukai.bishe.view.ITransactionCallBack;
import com.liukai.bishe.view.ITransactionUserTimeCallBack;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements IFindTransactionByUsernameCallBack,ITransactionUserTimeCallBack,ITransactionCallBack {


    private Unbinder mBind;

    private Context mContext = MainActivity.this;

    @BindView(R.id.bottomNavigationView)
    public BottomNavigationView mBottomNavigationView;

    @BindView(R.id.mainFragment)
    public FrameLayout mFrameLayout;

    @BindView(R.id.navigation_view)
    public NavigationView mNavigationView;

    @BindView(R.id.drawer_layout)
    public DrawerLayout drawer;

    @BindView(R.id.mainToolbar)
    MaterialToolbar mMaterialToolbar;

    @BindView(R.id.userHeadImg1)
    public CircleImageView mCircleImageView1;

//    @BindView(R.id.openNavigationView)
//    ImageView openNavigationView;

    private AnalysisFragment mAnalysisFragment;
    private SettingFragment mSettingFragment;
    private StateFragment mStateFragment;
    private TransactionFragment mTransactionFragment;
    private FragmentManager mFm;
    private FragmentTransaction mTransaction;
    private View mHeaderView;
    private CircleImageView mUserHeadImg;
    private IUpdateHeadImgPresenter mIUpdateHeadImgPresenter;

    private File mTmpFile;
    private File mCropImageFile;
    private TextView mTvUserInfo;
    private User mUserInfo;
    private LoadFragment mLoadFragment;
    private IFindTransactionByUsernamePresenter mIFindTransactionByUsernamePresenter;
    private ITransactionUserTimePresenter mITransactionUserTimePresenter;
    private ITransactionPresenter mITransactionPresenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();
        // 绑定ButterKnife
        mBind = ButterKnife.bind(this);
        initView();
        initFragment();
        initListener();
        judgePermission();

    }

    protected void judgePermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝

            // sd卡权限
            String[] SdCardPermission = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, SdCardPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCardPermission, 100);
            }

            //手机状态权限
            String[] readPhoneStatePermission = {Manifest.permission.READ_PHONE_STATE};
            if (ContextCompat.checkSelfPermission(this, readPhoneStatePermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, readPhoneStatePermission, 200);
            }

            //定位权限
            String[] locationPermission = {Manifest.permission.ACCESS_FINE_LOCATION};
            if (ContextCompat.checkSelfPermission(this, locationPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, locationPermission, 300);
            }

            String[] ACCESS_COARSE_LOCATION = {Manifest.permission.ACCESS_COARSE_LOCATION};
            if (ContextCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, ACCESS_COARSE_LOCATION, 400);
            }


            String[] READ_EXTERNAL_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, READ_EXTERNAL_STORAGE, 500);
            }

            String[] WRITE_EXTERNAL_STORAGE = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, WRITE_EXTERNAL_STORAGE, 600);
            }

        }else{
            //doSdCardResult();
        }
        //LocationClient.reStart();
    }

    private void initView() {
        // 侧边栏头部的组件
        mHeaderView = mNavigationView.getHeaderView(0);
        mUserHeadImg = mHeaderView.findViewById(R.id.userHeadImg);
        mTvUserInfo = mHeaderView.findViewById(R.id.userInfo);

        setSupportActionBar(mMaterialToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏标题
        mMaterialToolbar.setNavigationIcon(new CircleDrawable(getDrawable(R.drawable.img1), MainActivity.this, 20));
        mMaterialToolbar.setTitle("事务");
        mMaterialToolbar.setNavigationOnClickListener(view -> drawer.openDrawer(GravityCompat.START));

        setNickNameAndHeadImg(); // 显示昵称和头像

    }


    private void initData() {
        mUserInfo = Constants.getUserInfo();
        if (mUserInfo!=null){
            ToastUtil.log(mContext,mUserInfo.toString());
        }


    }

    /**
     *  初始化监听
     */
    private void initListener() {

        // 打开侧边栏点击事件
        mCircleImageView1.setOnClickListener(view -> {
            ToastUtil.show(mContext,"打开侧边栏");
            drawer.openDrawer(Gravity.LEFT);
        });

        // 侧边栏用户头像点击事件
        mUserHeadImg.setOnClickListener(view -> {
//            Intent intent = new Intent(MainActivity.this,UserInfoActivity.class);
//            startActivityForResult(intent,Constants.REQUEST_ChANGE_USERINFO);
//            String userHead = mUserInfo.getUserhead();
//            ShowBigPhoto showBigPhoto = new ShowBigPhoto(mContext,userHead,"1");
//            showBigPhoto.show();
        });

        // 侧边栏用户信息点击事件
        mTvUserInfo.setOnClickListener(view -> {
//            Intent intent = new Intent(MainActivity.this,UserInfoActivity.class);
//            startActivityForResult(intent,Constants.REQUEST_ChANGE_USERINFO);
        });

        // 主界面底部导航栏点击事件
        mBottomNavigationView.setOnNavigationItemSelectedListener(item -> {

            switch (item.getItemId()){

                case R.id.transaction:
                    switchFragment(mTransactionFragment);
                    ToastUtil.log(mContext,"任务");
                    mMaterialToolbar.setTitle("任务");
                    break;

                case R.id.state:
                    switchFragment(mStateFragment);
                    ToastUtil.log(mContext,"执行记录");
                    mMaterialToolbar.setTitle("执行记录");
                    break;

                case R.id.analysis:
                    switchFragment(mAnalysisFragment);
                    ToastUtil.log(mContext,"分析");
                    mMaterialToolbar.setTitle("分析");
                    break;

                case R.id.setting:
                    switchFragment(mSettingFragment);
                    ToastUtil.log(mContext,"排行榜");
                    mMaterialToolbar.setTitle("排行榜");
                    break;

            }

            return true;
        });

        // 侧边栏按钮点击事件
//        mNavigationView.setNavigationItemSelectedListener(item -> {
//
//            ToastUtil.show(mContext,item.getTitle().toString() );
//
//            return false;
//        });
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()){
                    case R.id.changeUserInfo :
                        Intent intent1 = new Intent(MainActivity.this,UserInfoActivity.class);
                        startActivityForResult(intent1,Constants.REQUEST_ChANGE_USERINFO);
                        break;

                    case R.id.rankList :
                        switchFragment(mSettingFragment);
                        ToastUtil.log(mContext,"排行榜");
                        mMaterialToolbar.setTitle("排行榜");
                        drawer.closeDrawers();
                        break;

                    case R.id.btnRecord :

                        TimePickerView pvTime = new TimePickerBuilder(mContext, (date, v) -> {
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Toast.makeText(mContext, date.getTime()+"", Toast.LENGTH_SHORT).show();
                            long timeMills = date.getTime();
                            Intent intent2 = new Intent(mContext,RecordActivity.class);
                            intent2.putExtra("timeMills",String.valueOf(timeMills));
                            mContext.startActivity(intent2);
                            drawer.closeDrawers();
                        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                                .setCancelText("取消")//取消按钮文字
                                .setSubmitText("确定")//确认按钮文字
                                .setTitleSize(20)//标题文字大小
                                .setTitleText("Title")//标题文字
                                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                                .isCyclic(true)//是否循环滚动
                                .setTitleColor(mContext.getColor(R.color.white))//标题文字颜色
                                .setSubmitColor(mContext.getColor(R.color.white))//确定按钮文字颜色
                                .setCancelColor(mContext.getColor(R.color.white))//取消按钮文字颜色
                                .setTitleBgColor(mContext.getColor(R.color.colorPrimary))//标题背景颜色 Night mode
                                .setBgColor(mContext.getColor(R.color.white))//滚轮背景颜色 Night mode
                                .setLabel("年","月","日","时","分","秒")//默认设置为年月日时分秒
                                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                                .isDialog(true)//是否显示为对话框样式
                                .setTextColorCenter(mContext.getColor(R.color.colorPrimary))
                                .setTextColorOut(mContext.getColor(R.color.colorNoSexGrey))
                                .build();
                        pvTime.show();

                        break;
                }

                return true;
            }
        });

    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {

        mAnalysisFragment = new AnalysisFragment();
        mSettingFragment = new SettingFragment();
        mStateFragment = new StateFragment();
        mTransactionFragment = new TransactionFragment();
        mLoadFragment = new LoadFragment();
        switchFragment(mLoadFragment);

        mIFindTransactionByUsernamePresenter = new IFindTransactionByUsernamePresenterImpl();
        // 注册按照用户名查找事务的Presenter
        mIFindTransactionByUsernamePresenter.registerCallback(this);
        mIFindTransactionByUsernamePresenter.getTransactionByName(mUserInfo.getUsername());

        mITransactionUserTimePresenter = new ITransactionUserTimePresenterImpl();
        mITransactionUserTimePresenter.registerCallback(this);
        mITransactionUserTimePresenter.findTransactionUserTimeByUserName(mUserInfo.getUsername());

        mITransactionPresenter = new ITransactionPresenterImpl();
        mITransactionPresenter.registerCallback(this);
        mITransactionPresenter.findTransactionTotal(mUserInfo.getUsername());

    }

    /**
     * 切换Fragment
     * @param baseFragment
     */
    private void switchFragment(BaseFragment baseFragment) {

        mFm = getSupportFragmentManager();
        mTransaction = mFm.beginTransaction();
        mTransaction.replace(R.id.mainFragment,baseFragment);
        mTransaction.commit();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ToastUtil.log(mContext,requestCode+"====>"+resultCode);
        if (requestCode == Constants.REQUEST_ChANGE_USERINFO && resultCode == RESULT_OK){
            mUserInfo = Constants.getUserInfo();
            ToastUtil.log(mContext,mUserInfo.toString());
            setNickNameAndHeadImg();
        }
    }

    private void setNickNameAndHeadImg(){
        // 显示头像
        if (mUserInfo!=null){
            ToastUtil.log(mContext,mUserInfo.toString());
        }
        if(mUserInfo.getUserhead()!=null && !mUserInfo.getUserhead().equals("")){
            Glide.with(this).load(mUserInfo.getUserhead()).into(mUserHeadImg);
            Glide.with(mContext).load(mUserInfo.getUserhead()).into(mCircleImageView1);
        }else{
            Glide.with(this).load(R.mipmap.img1).into(mUserHeadImg);
            Glide.with(mContext).load(R.mipmap.img1).into(mCircleImageView1);
        }

        // 显示昵称
        if(mUserInfo.getNickname()!=null && !mUserInfo.getNickname().equals("")){
            mTvUserInfo.setText(mUserInfo.getNickname());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Constants.setUser(new User());
        if (mBind != null) {
            mBind = null;
        }
        if (mIFindTransactionByUsernamePresenter != null) {
            mIFindTransactionByUsernamePresenter.unregisterCallback(this);
        }
    }

    private boolean quit = false; //设置退出标识

    @Override
    public void onBackPressed() {
        if (quit == false) { //询问退出程序
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            new Timer(true).schedule(new TimerTask() { //启动定时任务
                @Override
                public void run() {
                    quit = false; //重置退出标识
                }
            }, 2000); //2秒后运行run()方法
            quit = true;
        } else { //确认退出程序
            super.onBackPressed();
            Intent intent = new Intent();// 创建Intent对象
            intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
            intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
            startActivity(intent);// 将Intent传递给Activity
        }
    }

    /**
     * 获取该用户的所有事务
     * @param transactionMessageList
     */
    @Override
    public void transactionByName(TransactionMessageList transactionMessageList) {
        String code = transactionMessageList.getCode();
        if(code.equals("4001")){
            ToastUtil.log(mContext,"MainActivity===============>",
                    transactionMessageList.getTransactionList().toString());
            Constants.setTransactionList(transactionMessageList.getTransactionList());
        }
        switchFragment(mTransactionFragment);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_main, menu);
        return true;
    }

    /**
     * 获取该用户事务的执行情况
     * @param transactionUseTimes
     */
    @Override
    public void findTransactionUserTimeByUserName(List<TransactionUseTime> transactionUseTimes) {

        Constants.setTransactionUseTimeList(transactionUseTimes);

    }

    @Override
    public void result(Object object) {

    }

    @Override
    public void resultTrsaction(Object object) {

    }

    /**
     * 获取服务器返回的该用户每一项任务总的执行情况
     * @param transactionTotalList
     */
    @Override
    public void resultTransactionTotal(List<TransactionTotal> transactionTotalList) {
        Constants.setTransactionTotalList(transactionTotalList);
    }

}
